package com.justplay.mobilelocation;


import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.Gson;
import com.justplay.mobilelocation.UI.ContactsActivity;
import com.justplay.mobilelocation.bean.QuestLocalBean;
import com.justplay.mobilelocation.util.Config;
import com.justplay.mobilelocation.util.InputActivityUtil;
import com.justplay.mobilelocation.util.SharePreferencesUtil;
import com.sunshine.retrofit.HttpUtil;
import com.sunshine.retrofit.interfaces.ErrorFunListener;
import com.sunshine.retrofit.interfaces.Success;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static android.view.inputmethod.InputMethodManager.HIDE_NOT_ALWAYS;
import static com.justplay.mobilelocation.util.Config.kefuMobile;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {

    @Bind(R.id.map)
    MapView mMapView;
    @Bind(R.id.spinner)
    Spinner spinner;
    @Bind(R.id.tv_right_2)
    TextView tv_right_2;
    @Bind(R.id.textView5)
    TextView textView5;
    @Bind(R.id.textView6)
    TextView textView6;
    @Bind(R.id.et_inputNumber)
    EditText et_inputNumber;
    private AMap aMap;
    private MarkerOptions markerOption;


    LocationSource.OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;
    private Marker marker;
    private GeocodeSearch geocoderSearch;

    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        mMapView.onCreate(savedInstanceState);

        initMapView();
        initView();

        activate(new LocationSource.OnLocationChangedListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateUserLocalToNet(location);
            }
        });
        return view;
    }

    private void updateUserLocalToNet(Location location) {
        String userName = SharePreferencesUtil.getString("userName", "", getActivity());

        new HttpUtil.Builder("users/realTimeUpdateLocation")
                .Params("username", userName)
                .Params("latitude", location.getLatitude() + "")
                .Params("longitude", location.getLongitude() + "")

                .Tag(this)//需要取消请求的tag
                .Success(new Success() {
                    @Override
                    public void Success(String model) {

                    }
                }).ErrorEventFunc(new ErrorFunListener() {
            @Override
            public void ErrorFun(Object... values) {
                String value = (String) values[1];
            }
        })
                .post();
    }


    private void queryLocal() {

        new HttpUtil.Builder("users/findUserLocationByMobile")
                .Params("mobile", et_inputNumber.getText().toString())

                .Tag(this)//需要取消请求的tag
                .Success(new Success() {
                    @Override
                    public void Success(String model) {
                        QuestLocalBean questLocalBean = new Gson().fromJson(model, QuestLocalBean.class);
                        int flag = questLocalBean.getFlag();
                        if (flag == 1) {
                            double latitude = questLocalBean.getResult().getLatitude();
                            double longitude = questLocalBean.getResult().getLongitude();
                            LatLng latlng = new LatLng(latitude, longitude);
                            queryAddress(latlng);

//                            addMarkersToMap(latlng);
                        } else {
                            InputActivityUtil.gotoInputCodeActivity(getActivity());

                        }
                    }
                }).ErrorEventFunc(new ErrorFunListener() {
            @Override
            public void ErrorFun(Object... values) {
                String value = (String) values[1];
            }
        })
                .post();
    }

    private void queryAddress(LatLng latlng) {
         LatLonPoint latLonPoint = new LatLonPoint(latlng.latitude, latlng.longitude);

        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
    }


    /**
     * 在地图上添加marker
     *
     * @param latlng
     * @param address
     */
    private void addMarkersToMap(LatLng latlng, String address) {
        markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                .position(latlng)
//                .title("标题")
                .snippet(address)
                .draggable(true);
        marker = aMap.addMarker(markerOption);
        marker.showInfoWindow();
        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(8);

        if (aMap != null) {
            aMap.moveCamera(mCameraUpdate);
        }
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                latlng, 15));
    }

    private void initView() {
        tv_right_2.setText("开始定位");
    }

    private void initMapView() {
        aMap = mMapView.getMap();
        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(3);

        if (aMap != null) {
            aMap.moveCamera(mCameraUpdate);
        MyLocationStyle myLocationStyle;
//        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
//        myLocationStyle.interval(6000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
//        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(false);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        }


        geocoderSearch = new GeocodeSearch(getActivity());
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                String address = "";
                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                     address = result.getRegeocodeAddress().getFormatAddress() + "附近";
                }
                addMarkersToMap(new LatLng(result.getRegeocodeQuery().getPoint().getLatitude(),result.getRegeocodeQuery().getPoint().getLongitude()),address);
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });

    }

    /**
     * 激活定位
     */
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(getActivity());
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation amapLocation) {
                    if (mListener != null && amapLocation != null) {
                        if (amapLocation != null
                                && amapLocation.getErrorCode() == 0) {
                            mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
//                            Toast.makeText(getActivity(), "显示系统小蓝点", Toast.LENGTH_SHORT).show();
                        } else {
                            String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                            Log.e("AmapErr", errText);
                        }
                    }
                }
            });
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    /**
     * 停止定位
     */
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    @Override
    public void onDestroyView() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        super.onDestroyView();
        ButterKnife.unbind(this);

        deactivate();
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @OnClick({R.id.tv_right_2, R.id.textView5, R.id.textView6, R.id.iv_contast})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right_2:
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), HIDE_NOT_ALWAYS);


                aMap.clear();
                String userName = SharePreferencesUtil.getString("userName", "", getActivity());
                String mobile = SharePreferencesUtil.getString(kefuMobile, "", getActivity());

                String inputPhone = et_inputNumber.getText().toString().trim();

                Boolean havedBuy = SharePreferencesUtil.getBoolean("havedBuy", false, getActivity());

                if (inputPhone.equals(userName)||inputPhone.equals(mobile)||havedBuy) {
                    queryLocal();
                }  else {
                    InputActivityUtil.gotoInputCodeActivity(getActivity());

                }
                break;
            case R.id.textView5:
                InputActivityUtil.gotoInputCodeActivity(getActivity());
                break;
            case R.id.textView6:
                if (aMap.getMapType() == AMap.MAP_TYPE_SATELLITE) {
                    aMap.setMapType(aMap.MAP_TYPE_NORMAL);
                } else {
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                }
                break;
            case R.id.iv_contast:
                startActivityForResult(new Intent(getActivity(), ContactsActivity.class), Config.REQUESTCODE_CONTASTS);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.REQUESTCODE_CONTASTS && resultCode == RESULT_OK) {

            et_inputNumber.setText(data.getStringExtra("phone"));
        }
    }
}
